package com.cqh.filter;

import com.alibaba.fastjson.JSON;
import com.cqh.common.BaseContext;
import com.cqh.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路劲匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;



        String requestURI=request.getRequestURI();
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        log.info("拦截到请求：{}",request.getRequestURI());
        HttpSession session=request.getSession();
        if (check(urls,requestURI)){
            chain.doFilter(request,response);
            return;
        }

        if (session.getAttribute("employee")!=null){
            log.info("用户已经登路，用户id 为{}",request.getSession().getAttribute("employee"));
            Long empid=(Long)request.getSession().getAttribute("employee");
            log.info("ruquest携带的数据{}",empid);
            BaseContext.setThreadLocal(empid);
            chain.doFilter(request,response);
            return;

        }
        if (session.getAttribute("user")!=null){
            log.info("用户已经登路，用户id 为{}",request.getSession().getAttribute("user"));
            Long userid=(Long)request.getSession().getAttribute("user");
            log.info("ruquest携带的数据{}",userid);
            BaseContext.setThreadLocal(userid);
            chain.doFilter(request,response);
            return;

        }
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        return;
    }

    /**
     * 路径匹配，检查请求是否放行
     * @param requestUrl
     * @return
     */
    public boolean check(String[] urls,String requestUrl){
        for (String url : urls) {
           boolean match= PATH_MATCHER.match(url,requestUrl);
            if (match){
                return true;
            }
        }
        return false;
    }


}
